//
//  PublishHistoryVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/8.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import PullToRefresh
import HandyJSON

class PublishHistoryVC: UIViewController , UITableViewDelegate, UITableViewDataSource {

    let mTableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    
    let empayView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    
    let emptyLabel = UILabel.init(frame: CGRect.init(x: 0, y: Const.SCREEN_HEIGHT/2, width: Const.SCREEN_WIDTH, height: 30))
    
    var pageNum = 0
    var models:[XianhuoModel] = []
    let bottomRefreher = PullToRefresh(position: .bottom)
    
    deinit {
        print("self:\(self.mTableView)")
        if let btm = mTableView.bottomPullToRefresh{
            print("btm:\(btm),bottomRefreher:\(bottomRefreher)")
            self.mTableView.removePullToRefresh(at: .bottom)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(mTableView)
        self.view.addSubview(empayView)
        self.view.addSubview(emptyLabel)
        self.view.backgroundColor = Const.WTM_LIGHTGRAY
        self.mTableView.backgroundColor = Const.WTM_WHITE_SMOKE
        self.mTableView.delegate = self
        self.mTableView.dataSource = self
        self.mTableView.separatorStyle = .none
        self.mTableView.contentInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
        self.addRefreshFooter()
        self.title = "我的发布"
        self.empayView.isHidden = true
        self.refresh()
        
        self.addRefreshFooter()
    }
    
    func addRefreshFooter() -> Void {
        self.mTableView.addPullToRefresh(bottomRefreher) { [weak self] in
            if self == nil {
                return
            }
            self!.loadmore()
        }
    }
    
    func removeRefreshFooter() -> Void {
        if bottomRefreher != nil {
            self.mTableView.removePullToRefresh(at: .bottom)
        }
    }
    
    func getURL() -> String{
        return NetworkManager.XIANHUO_MINE_LIST
    }

    func refresh() {
        
        let params = ["page":"1","userid":User.get.userId]
        
        _ = NetworkManager.GET(getURL(),params:params) { (status, response) in
            self.mTableView.endRefreshing(at: .top)
            self.models.removeAll()

            if(status){
                
                for dic in response.wtmList {
                    let member = JSONDeserializer<XianhuoModel>.deserializeFrom(dict:dic as? NSDictionary)
                    self.models.append(member!)
                }
                if self.models.isEmpty {
                    self.empayView.isHidden = false
                    self.emptyLabel.text = self.emptyHint()
                }
                self.mTableView.reloadData()
            }
        }
    }
    
    func loadmore() {
        let pageNumStr = String(pageNum)
        let params = ["page":pageNumStr,"userid":User.get.userId]
        
        _ = NetworkManager.GET(getURL(),params:params) { (status, response) in
            self.mTableView.endRefreshing(at: .bottom)
            
            for dic in response.wtmList {
                let member = JSONDeserializer<XianhuoModel>.deserializeFrom(dict:dic as? NSDictionary)
                self.models.append(member!)
            }
            if response.wtmList.count < 10 {
                self.removeRefreshFooter()
            }
            self.mTableView.reloadData()
            
        }
    }
    
    // MARK :- tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let xianhuo = models[indexPath.row]
        return self.heightOfXianhuo(xianhuo)
    }
    
    func heightOfXianhuo(_ xianhuo: XianhuoModel) -> CGFloat {
        
        return XianhuoListCell.height
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let xianhuo = self.models[indexPath.row]
        
        if let cell:XianhuoListCell = tableView.dequeueReusableCell(withIdentifier: "XianhuoListCell") as? XianhuoListCell {
            cell.categoryTV.text = xianhuo.channelname
            cell.companyTV.text = xianhuo.company
            cell.dateTV.text = xianhuo.getDate()
//            cell.specificationTV.text = xianhuo.specification
            cell.imgView.kf.setImage(with:URL(string:xianhuo.productpic))
//            cell.setPrice(xianhuo.price)
            self.setStatus(xianhuo.audit, onCell: cell)
            return cell
        }
        let cell:XianhuoListCell = XianhuoListCell.init(style: .default, reuseIdentifier: "XianhuoListCell")
        cell.categoryTV.text = xianhuo.channelname
        cell.companyTV.text = xianhuo.company
        cell.factoryTV.text = xianhuo.factory
        cell.dateTV.text = xianhuo.getDate()
//        cell.specificationTV.text = xianhuo.specification
        cell.imgView.kf.setImage(with:URL(string:xianhuo.productpic))
        cell.dateTV.text = xianhuo.getDate()
//        cell.setPrice(xianhuo.price)
        self.setStatus(xianhuo.audit, onCell: cell)
        return cell
    }
    
    func setStatus(_ audit:String, onCell:XianhuoListCell){
        onCell.locationImg.removeFromSuperview()
        onCell.locationTV.textColor = UIColor.red
        if ("0" == audit){
            onCell.locationTV.text = "待审核"
        }else if ("1" == audit){
            onCell.locationTV.text = "审核通过"
        }else if ("2" == audit){
            onCell.locationTV.text = "审核不通过"
        }
        
        onCell.locationTV.frame = CGRect.init(x: Int(Const.SCREEN_WIDTH - 60), y: 5, width: 50, height: 45);
        onCell.locationTV.textAlignment = .right

    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        let xianhuo : XianhuoModel = self.models[indexPath.row]
        let vc = XianhuoDetailVC2.init()
        vc.url = vc.SHARE_URL + xianhuo.xianhuoId + "&fromApp=1"
        vc.model = xianhuo
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func emptyHint() ->String {
        return "您还没有发布数据哦～"
    }
    
}
